package top.jiangyixin.food.platform.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeoutException;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import top.jiangyixin.food.platform.order.config.MqDataConfig;
import top.jiangyixin.food.platform.order.constant.OrderStatusEnum;
import top.jiangyixin.food.platform.order.mapper.OrderDetailMapper;
import top.jiangyixin.food.platform.order.pojo.dto.OrderMessageDTO;
import top.jiangyixin.food.platform.order.pojo.model.OrderDetailModel;
import top.jiangyixin.food.platform.order.pojo.vo.OrderCreateVO;
import top.jiangyixin.food.platform.order.service.OrderService;

/**
 * @author jiangyixin
 * @version 1.0
 * @date 2021/6/22 下午2:30
 */
@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderDetailMapper, OrderDetailModel>
        implements OrderService  {
    
    @Resource
    private MqDataConfig mqDataConfig;
    private final ObjectMapper objectMapper = new ObjectMapper();
    
    @Override
    public void createOrder(OrderCreateVO orderCreateVO) throws IOException, TimeoutException {
        log.info("Create Order: {}", orderCreateVO);
        OrderDetailModel order = new OrderDetailModel();
        order.setAddress(orderCreateVO.getAddress());
        order.setAccountId(orderCreateVO.getAccountId());
        order.setProductId(orderCreateVO.getProductId());
        order.setStatus(OrderStatusEnum.ORDER_CREATING);
        order.setDate(new Date());
        save(order);
    
        OrderMessageDTO orderMessageDTO = new OrderMessageDTO();
        orderMessageDTO.setOrderId(order.getId());
        orderMessageDTO.setProductId(order.getProductId());
        orderMessageDTO.setAccountId(order.getAccountId());
    
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        try (Connection connection = connectionFactory.newConnection();
                Channel channel = connection.createChannel()){
            String message = objectMapper.writeValueAsString(orderMessageDTO);
            channel.basicPublish("exchange.order.restaurant", "key.restaurant", null, message.getBytes());
        }
    }
}
